package com.platform.filter;
import com.platform.base.BaseService;
import com.platform.common.Const;
import com.platform.dao.RolePermissionMapper;
import com.platform.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 过滤器，用于权限控制
 */
public class UserFileter extends BaseService implements Filter {




    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }



    /**
     * 访问前控制
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        /*HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        String requestUrl = httpRequest.getRequestURI();
        HttpSession session = httpRequest.getSession(true);
        Object object = session.getAttribute(Const.CURRENT_USER);
        //判断是否登录
        User user = object == null ? null : (User) object;
        if (user == null) {
            return;
        }
        if(user != null){
            //获取访问路径方法

            if(null == rolePermissionMapper){
                ApplicationContext ac =
                        WebApplicationContextUtils.getWebApplicationContext(((HttpServletRequest) servletRequest).getSession().getServletContext());
                rolePermissionMapper = (RolePermissionMapper)ac.getBean("rolePermissionMapper");
            }
            //查询该用户是否拥有该访问路径的权限，如没有，则跳至404页面
            Integer countResult = rolePermissionMapper.checkByUserIdAndUrl(user.getUsername(),requestUrl);
            if(null == countResult || countResult == 0){
                //httpResponse.sendRedirect(PropertiesUtil.getProperty("error.404"));
                return;
            }
        }*/
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }

    @Override
    public void destroy() {

    }

    /**
     * 判断是否为Ajax请求
     *
     * @param request HttpServletRequest
     * @return 是true, 否false
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        return request.getRequestURI().startsWith("/api");
        /*String requestType = request.getHeader("X-Requested-With");
        return requestType != null && requestType.equals("XMLHttpRequest");*/
    }
}
